import { config } from './config.js';
import { HTTP } from './utils/http.js';
import { localStorage } from './utils/storage.js';

const _http = new HTTP();
const _localStorage = new localStorage();

App({
  onLaunch: function () {
    // 获取系统信息
    wx.getSystemInfo({
      success: result => {
        this.globalData.windowHeight = result.windowHeight;
        this.globalData.screenHeight = result.screenHeight;
      }
    });
  },
  // 初始化 以防小程序缓存被清理获取不到用户信息
  init: function() {
      if(_localStorage.getItem('code') == '') {
        this.getLoginCode()
      }
      if(_localStorage.getItem('openid') == '') {
        this.getUserOpenid()
      }
  },
  // 获取code
  getLoginCode() {
    wx.login({
      success: res => {
        let code = res.code;
        if(code) {
          this.globalData.code = code
          _localStorage.setItem('code', code);
        }
      },
      fail: err => {
        console.log('获取code失败：', err)
      }
    })
  },
  // 获取用户信息
  getUserInfo() {
    wx.getUserInfo({
      success: res => {
        let userinfo = res.userInfo;
        if (userinfo) {
          this.globalData.userInfo = userinfo;
          _localStorage.setItem('userInfo', userinfo);
        }
      },
      fail: err => {
        console.log('获取用户信息失败：', err)
      }
    })
  },
  // 请求服务器取用户openid
  getUserOpenid(callBack) {
    this.getLoginCode();
    let code = this.getCode();
    _http.request({
      url: 'app/GetOpenid',
      method: 'POST',
      data: {
        code: code,
        appid: config.APPID,
        appsecret: config.APPSECRET
      }
    })
    .then(res => {
      let openid = res.data.openid;
      if(openid) {
        this.globalData.openId = openid;
        _localStorage.setItem('openid', openid)
      }
      if(callBack) {
        callBack(res)
      }
    })
  },
  // 检查用户是否已授权
  isAuthize() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          // 用户已授权
          if (res.authSetting['scope.userInfo']) {
            this.init();
            resolve(true)
          }else {
            resolve(false)
          }
        },
        fail: err => {
          reject(err)
        }
      })
    })
  },
  // 登录授权
  loginAuthize() {
    this.getUserOpenid( res => {
      res = res.data
      if (res.regis == false) {
        _http.request({
          url: 'app/regisUser',
          data: {
            name: _localStorage.getItem('userInfo').nickName,
            head: _localStorage.getItem('userInfo').avatarUrl,
            openid: res.openid
          }
        })
        .then(res => {
          if(res.code == 2) {
            console.log('首次登录注册成功：', res)
          }
        })
      }
      wx.showToast({
        title: '授权成功',
        icon: 'success',
        duration: 2000,
        success: res => {
          setTimeout(() => {
            wx.switchTab({
              url: '../home/index/index'
            })
          }, 500)
        }
      })
    })
  },
  // 显示授权
  showAuthize() {
    wx.showModal({
      title: '提示',
      content: '请先授权',
      success: res => {
        if (res.confirm) {
          this.getLoginCode();
          wx.redirectTo({
            url: '/pages/login/index',
          })
        } else if (res.cancel) {
          console.log('这个用户不想授权')
        }
      }
    })
  },
  // 获取openid
  getOpenId () {
    let openid = this.globalData.openId || _localStorage.getItem('openid');
    if (openid) {
      return openid
    }
  },
  // 获取code 
  getCode() {
    let code = this.globalData.code || _localStorage.getItem('code');
    if (code) {
      return code
    }
  },
  globalData: {
    code: null,
    openId: null,
    windowHeight: null,
    screenHeight: null
  }
})